package com.tianji.remark.service.impl;


import cn.hutool.core.bean.BeanUtil;
import com.tianji.api.dto.remark.LikedTimesDTO;
import com.tianji.common.autoconfigure.mq.RabbitMqHelper;
import com.tianji.common.constants.MqConstants;
import com.tianji.common.utils.StringUtils;
import com.tianji.remark.domain.dto.LikeRecordFormDTO;
import com.tianji.remark.domain.po.LikedStat;
import com.tianji.remark.mapper.LikedStatMapper;
import com.tianji.remark.service.ILikedStatService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 点赞统计表 服务实现类
 * </p>
 *
 * @author taohongrun
 * @since 2025-02-07
 */
@Service
@RequiredArgsConstructor
public class LikedStatServiceImpl extends ServiceImpl<LikedStatMapper, LikedStat> implements ILikedStatService {

    private final RabbitTemplate rabbitTemplate;

    @Override
    @Transactional
    public void updateLikedTimes(LikeRecordFormDTO formDTO) {
        // 1.查询最新点赞数量
        LikedStat stat = lambdaQuery().eq(LikedStat::getBizId, formDTO.getBizId()).one();
        if (stat == null) {
            // 2.新增
            stat = new LikedStat();
            stat.setLikedTimes(1);
            stat.setBizId(formDTO.getBizId());
            stat.setBizType(formDTO.getBizType());
            stat.setCreateTime(LocalDateTime.now());
            stat.setUpdateTime(LocalDateTime.now());
            save(stat);
        }else{
            // 3.更新点赞数量
            lambdaUpdate().eq(LikedStat::getId,stat.getId())
                    .set(formDTO.getLiked(),LikedStat::getLikedTimes,"liked_times = liked_times +1")
                    .set(!formDTO.getLiked(),LikedStat::getLikedTimes,"liked_times =liked_times - 1")
                    .update();
        }
        // 3.发送MQ消息
        // 3.1.获取最新点赞数量
        stat = getById(stat.getId());
        // 3.2.发送消息
        rabbitTemplate.convertAndSend(
                MqConstants.Exchange.LIKE_RECORD_EXCHANGE,
                StringUtils.format(MqConstants.Key.LIKED_TIMES_KEY_TEMPLATE, formDTO.getBizType()),
                LikedTimesDTO.of(stat.getBizId(), stat.getLikedTimes()));
    }

    @Override
    public void updateLikedTimesBatch(String bizType, List<LikedTimesDTO> list) {
        // 1.批量保存点赞数量
        //1.1saveOrUpdate必须先查询旧数据
        List<LikedStat> oldList = lambdaQuery()
                .in(LikedStat::getBizId, list.stream().map(LikedTimesDTO::getBizId).collect(Collectors.toList()))
                .list();
        Map<Long, Long> oldLikedTimesHash = oldList.stream().collect(Collectors.toMap(LikedStat::getBizId, LikedStat::getId));
        List<LikedStat> likedStatList = list.stream()
                .map(item -> {
                    LikedStat likedStat = BeanUtil.copyProperties(item, LikedStat.class);
                    likedStat.setUpdateTime(LocalDateTime.now());
                    if(oldLikedTimesHash.containsKey(item.getBizId())) likedStat.setId(oldLikedTimesHash.get(item.getBizId()));
                    likedStat.setCreateTime(LocalDateTime.now());
                    return likedStat;
                })
                .collect(Collectors.toList());
        if(likedStatList.isEmpty()) return;
        saveOrUpdateBatch(likedStatList);

        // 2.发送MQ消息
        rabbitTemplate.convertAndSend(
                MqConstants.Exchange.LIKE_RECORD_EXCHANGE,
                StringUtils.format(MqConstants.Key.LIKED_TIMES_KEY_TEMPLATE, bizType),
                list);
    }
}
